package com.alfred.redis.intercept;

import com.alfred.redis.annotation.ControllerLimit;
import com.alfred.redis.constant.RedisLimtCodeEnum;
import com.alfred.redis.exception.ServiceException;
import com.alfred.redis.limit.RedisLimit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * redis限流拦截器，也可以采用Aop方式(SpringMVC 的拦截器本质也是 AOP)
 */
@Slf4j
@Component
public class CustomInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private RedisLimit redisLimit;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //redisLimit为null直接返回失败
        if (null == redisLimit) {
            throw new ServiceException(RedisLimtCodeEnum.SERVICE_REDIS_LIMIT_IS_NULL.getCode(), RedisLimtCodeEnum.SERVICE_REDIS_LIMIT_IS_NULL.getMessage());
        }
        //判断请求是否属于方法的请求
        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            ////获取方法中的注解,看是否有该注解
            ControllerLimit controllerLimit = method.getMethodAnnotation(ControllerLimit.class);
            if (null != controllerLimit) {
                //判断是否被限流
                boolean limit = redisLimit.limit();
                if (!limit) {
                    //被限流了，直接丢弃任务快速响应到客户端
                    log.warn("request current limit");
                    throw new ServiceException(RedisLimtCodeEnum.SERVICE_REQUEST_CURRENT_LIMIT.getCode(), RedisLimtCodeEnum.SERVICE_REQUEST_CURRENT_LIMIT.getMessage());
                }
            }
        }
        return super.preHandle(request, response, handler);
    }
}
